/*
 * @Description: 左侧菜单数据获取服务
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-10-07 19:40:23
 * @LastEditTime: 2021-10-09 20:51:30
 */
const path = require('path')
const permissionAPIDAO = require(path.join(process.cwd(), '/dao/PermissionAPIDAO'))
const dao = require(path.join(process.cwd(), 'dao/DAO'))
const _ = require('lodash')

/**
 * @description: 根据权限返回菜单数据
 * @param {*} rid
 * @param {*} keyRolePermissions
 * @param {*} cb
 * @return {*}
 */
function authFn(rid, keyRolePermissions, cb) {
  permissionAPIDAO.list((err, permissions) => {
    if (!permissions) return cb('获取权限数据失败 !permissions')

    let rootPermissionsResult = {}
    // console.log(permissions)

    // 生成一级菜单
    for (row in permissions) {
      // console.log(permissionsPart[row].ps_level)
      let permission = permissions[row]
      if (permission.ps_level == 0) {
        if (rid != 0) {
          if (!keyRolePermissions[permission.ps_id]) continue
        }
        rootPermissionsResult[permission.ps_id] = {
          id: permission.ps_id,
          authName: permission.ps_name,
          path: permission.ps_api_path,
          children: [],
          order: permission.ps_api_order
        }
      }
    }

    // 添加二级菜单
    for (row in permissions) {
      // console.log(permissionsPart[row].ps_level)
      let permission = permissions[row]
      if (permission.ps_level == 1) {
        if (rid != 0) {
          if (!keyRolePermissions[permission.ps_id]) continue
        }
        let parentPermissionResult = rootPermissionsResult[permission.ps_pid]
        if (parentPermissionResult) {
          parentPermissionResult.children.push({
            id: permission.ps_id,
            authName: permission.ps_name,
            path: permission.ps_api_path,
            children: [],
            order: permission.ps_api_order
          })
        }
      }
    }

    // 排序
    result = _.values(rootPermissionsResult)
    result = _.sortBy(result, 'order')
    for (idx in result) {
      subresult = result[idx]
      subresult.children = _.sortBy(subresult.children, 'order')
    }

    return cb(null, result)
  })
}

/**
 * @description: 获取菜单数据
 * @param {*} userInfo
 * @param {Function} cb
 * @return {*}
 */
module.exports.getLeftMenus = function (userInfo, cb) {
  if (!userInfo) return cb('无权限访问')
  rid = userInfo.rid

  if (rid == 0) {
    console.log('rid === 0 ?')
    authFn(rid, null, cb)
  } else {
    dao.show('RoleModel', userInfo.rid, function (err, role) {
      if (err || !role) return cb('无权限访问')

      rolePermissions = role.ps_ids.split(',')
      keyRolePermissions = {}
      for (idx in rolePermissions) {
        keyRolePermissions[rolePermissions[idx]] = true
      }

      authFn(rid, keyRolePermissions, cb)
    })
  }
}
